package member;

import javax.servlet.http.*;

import model.*;

import org.apache.struts.action.*;
import org.apache.struts.actions.*;
import org.apache.struts.config.*;

import util.*;

public class LoginAction extends DispatchAction {
	
	public ActionForward login(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		MemberForm mf = (MemberForm)form;
		MemberDAO memberDAO = new MemberDAO();
		
		String rememberID = request.getParameter("cookiemid");
		rememberID = rememberID!=null?rememberID:"null";
		System.out.println("쿠키사용여부 : "+rememberID);
		
		String mid = mf.getMid().toLowerCase();
		String mpass = mf.getMpass();
		
		Member member = memberDAO.getMemberByMid(mid);
		ActionErrors errors = new ActionErrors();
		if(mid==null){
			mid="";
		}
		if(member.getMid()!=null){
			if(member.getMpass().equals(mpass)){
				ActionMessage message = new ActionMessage("로그인 성공",false);
				HttpSession session = request.getSession();
				User user = new User();
				user.setLogon(true);
				user.setMid(mid);
				user.setUserInfo(member);
				user.setMcnick(MemberCommunityDAO.getCommunityNick(mid, 5));
//				user.setCono("2");
//				user.setBname("자유게시판");
				
//				쪽지대응---------------------
				/*MessageDAO msg = new MessageDAO();
				int msgcnt = msg.getMessageCount(mid, 0);
				
				if(msgcnt == 0)
				{
					user.setMsg("새로운 메세지가 없습니다.");
				}
				else
				{
					user.setMsg(msgcnt + "건의 쪽지가 도착했습니다");
				}*/
				//-----------------------------
				
				session.setAttribute("user", user);
				errors.add("error",message);
				
				if(rememberID.equals("on")){
					Cookie cookie = new Cookie("cookiemid",user.getMid());
					cookie.setMaxAge(60*60*24*30);
					cookie.setPath("/");
					System.out.println("Cookie On : "+cookie);
					response.addCookie(cookie);				
				} else {
					Cookie cookie = new Cookie("cookiemid",null);
					cookie.setValue("");							
					cookie.setPath("/");
					System.out.println("Cookie Off : "+cookie);					
					response.addCookie(cookie);				
				}
				
				
				
		
			} else {
				ActionMessage message = new ActionMessage("암호 인증 실패",false);
				mf.setMpass(null);
				errors.add("error",message);
			}
		} else {
			ActionMessage message = new ActionMessage("존재하지 않는 아이디",false);
			mf.setMpass(null);
			errors.add("error",message);
		}
		
		return mapping.findForward("login");
	}

	
	public ActionForward logout(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
	
		MemberForm mf = (MemberForm)form;
		HttpSession session = request.getSession();
		session.setAttribute("user", null);

		return mapping.findForward("login");
	}

	
}
